package com.fms.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fms.common.vo.Result;
import com.fms.sys.entity.User;
import com.fms.sys.service.IUserService;
import com.fms.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.time.LocalDateTime;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author fjt
 * @since 2024-04-21
 */
@RestController // 前后端交互的是json数据，格式要统一，json.cn编译
@RequestMapping("/user")
// @CrossOrigin //跨域处理
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private IUserService userService; // 装配service对象

    @Autowired
    private PasswordEncoder passwordEncoder;

    @GetMapping("/all") // 请求查询所有的数据
    public Result<List<User>> getAllUser() {
        List<User> list = userService.list(); // userService内置了增删改查方法，调用即可
        return Result.success(list, "查询成功");
    }

    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> loginData) {
        try {
            // 创建用户对象
            User user = new User();
            user.setUsername(loginData.get("username"));
            user.setPassword(loginData.get("password"));

            // 调用service进行登录
            Map<String, Object> data = userService.login(user);
            if (data != null) {
                return Result.success(data);
            }
            return Result.fail(20002, "用户名或密码错误");
        } catch (RuntimeException e) {
            return Result.fail(20003, e.getMessage());
        }
    }

    @GetMapping("/info")
    public Result<Map<String, Object>> getUserInfo(@RequestParam("token") String token) {
        // 根据token获取用户信息，redis
        Map<String, Object> data = userService.getUserInfo(token);
        if (data != null) {
            return Result.success(data);
        }
        return Result.fail(20003, "用户信息获取失败");
    }

    @PostMapping("/logout")
    public Result<?> logout(@RequestHeader("X-Token") String token) {
        userService.logout(token);
        return Result.success("注销成功");
    }

    @GetMapping("/list")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Map<String, Object>> getUserList(
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "pageNo") Long pageNo,
            @RequestParam(value = "pageSize") Long pageSize) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasLength(username), User::getUsername, username);
        wrapper.eq(StringUtils.hasLength(phone), User::getPhone, phone);
        wrapper.orderByDesc(User::getId);// 用户ID降序排序

        Page<User> page = new Page<>(pageNo, pageSize);
        userService.page(page, wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("total", page.getTotal());// 返回参数，前后端统一名称
        data.put("rows", page.getRecords()); // 返回查询结果集

        return Result.success(data);
    }

    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> addUser(@RequestBody User user) { // RequestBody注解是将json数据转化成user对象
        // 密码加密处理，用BCryptPasswordEncoder，涉及登录逻辑改动：1、密码加密存储到db;2、登录时db和传入的比较
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userService.save(user);
        return Result.success("新增用户成功");
    }

    // 修改用户
    @PutMapping
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> updateUser(@RequestBody User user) {
        user.setPassword(null);
        userService.updateById(user);
        return Result.success("修改用户成功");
    }

    // 要根据ID获取对应的用户信息
    @GetMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<User> getUserById(@PathVariable("id") Integer id) {
        User user = userService.getById(id);
        return Result.success(user);
    }

    // 删除用户
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<User> deleteUserById(@PathVariable("id") Integer id) {
        userService.removeById(id);
        return Result.success("删除用户成功");
    }

    // 修改密码
    @PutMapping("/password")
    public Result<?> updatePassword(@RequestBody Map<String, String> passwordData) {
        try {
            Long userId = JwtUtils.getCurrentUserId();
            User user = userService.getById(userId);

            if (user == null) {
                return Result.fail(20002, "用户未登录或不存在");
            }

            String oldPassword = passwordData.get("oldPassword");
            String newPassword = passwordData.get("newPassword");

            // 验证旧密码
            if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
                return Result.fail("旧密码不正确");
            }

            // 加密新密码
            String encodedNewPassword = passwordEncoder.encode(newPassword);
            user.setPassword(encodedNewPassword);
            userService.updateById(user);

            return Result.success("密码修改成功");
        } catch (Exception e) {
            return Result.fail(20002, "密码修改失败: " + e.getMessage());
        }
    }

    // 修改个人信息
    @PutMapping("/profile")
    public Result<?> updateProfile(@RequestBody User user) {
        // 获取当前登录用户ID
        Long userId = JwtUtils.getCurrentUserId();
        // 设置用户ID，确保只能修改自己的信息
        user.setId(userId);
        // 不允许修改密码和用户名
        user.setPassword(null);
        user.setUsername(null);
        user.setRole(null); // 不允许通过此接口修改角色
        user.setStatus(null); // 不允许通过此接口修改状态
        // 更新用户信息
        userService.updateById(user);
        return Result.success("更新个人信息成功");
    }

    @GetMapping("/profile")
    public Result<User> getUserProfile() {
        try {
            // 获取当前登录用户ID
            Long userId = JwtUtils.getCurrentUserId();
            // 查询用户信息
            User user = userService.getById(userId);
            if (user == null) {
                return Result.fail(20002, "获取用户信息失败");
            }
            // 清除敏感信息
            user.setPassword(null);
            return Result.success(user, "获取用户信息成功");
        } catch (Exception e) {
            return Result.fail(20002, e.getMessage());
        }
    }

    /**
     * 更新用户状态（启用/禁用）
     */
    @PutMapping("/{userId}/status/{status}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> updateUserStatus(@PathVariable("userId") Long userId, @PathVariable("status") Integer status) {
        userService.updateUserStatus(userId, status);
        return Result.success("用户状态更新成功");
    }

    @GetMapping("/stats")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Map<String, Object>> getUserStats() {
        Map<String, Object> stats = userService.getUserStats();
        return Result.success(stats);
    }

    @PostMapping("/register")
    public Result<?> registerUser(@RequestBody User user) {
        try {
            // 设置默认角色为普通用户
            user.setRole("USER");

            // 保存用户到数据库
            boolean success = userService.save(user);
            if (success) {
                return Result.success("用户注册成功");
            } else {
                return Result.fail("用户注册失败，请检查用户名或邮箱是否已存在");
            }
        } catch (Exception e) {
            log.error("用户注册失败", e);
            return Result.fail("用户注册失败：" + e.getMessage());
        }
    }

}
